package com.example.blog.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author 郑涵文
 **/
public class MyInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(MyInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String name = method.getName();
        log.info("====拦截到了方法：{}，在该方法执行之前执行====", name);

        Cookie[] cookies = request.getCookies();
        String token = (String)request.getSession().getAttribute("token");
        System.out.println(token);
        if (cookies.length>0||cookies!=null){

            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())&&cookie.getValue().equals(token)){
                    return true;
                }
            }
        }
        return false;
    }

}
